package com.example.zrq1010110087.graceplayer.main;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.zrq1010110087.graceplayer.R;
import com.example.zrq1010110087.graceplayer.data.MediaPlayerUser;
import com.example.zrq1010110087.graceplayer.data.Music;
import com.example.zrq1010110087.graceplayer.data.Sdcard_MusicList;
import com.example.zrq1010110087.graceplayer.format.FormatUntils;
import com.example.zrq1010110087.graceplayer.theme.ThemeUntils;

import java.util.ArrayList;

import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;

public class MainActivity extends Activity {
   //设置全局引用
    private RelativeLayout root_Layout;
    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_Play;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ListView list;
    private TextView tv_currentTime;
    private TextView tv_durationTime;
    private  TextView tv_music;
    private SeekBar seekBar;
    private ArrayList<Music> musicArrayList;
    private MediaPlayerUser mediaPlayerUser;
    private MusicBroadcastReceiver musicReceiver;
    private StatusChangedReceiver statusChangedReceiver;
    private ThemeUntils themeUntils;
    private Handler seekBarHandler;
    private int currentTime=0;
    private int durationTime=0;
    private final int  PROGRESS_INCREASE=1;
    private final int PROGRESS_PAUSE=2;
    private  final int PROGRESS_RESET=3;
    private  int music_State;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewByI();
        bindReceiver();
        registerListener();
        initMusicList();
        initListView();
        checkMusicFile();
        initSeekBarHandler();


    }
    //绑定对象
    private void findViewByI(){

         imgBtn_Previous= (ImageButton) findViewById(R.id.button_previous);
        imgBtn_Play= (ImageButton) findViewById(R.id.button_play);
        imgBtn_Stop= (ImageButton) findViewById(R.id.button_stop);
        imgBtn_Next= (ImageButton) findViewById(R.id.button_next);
        list=(ListView)findViewById(R.id.listview);
        tv_currentTime=(TextView)findViewById(R.id.tv_currentTime);
        tv_durationTime=(TextView)findViewById(R.id.tv_durationTime);
        seekBar=(SeekBar)findViewById(R.id.seekBar_music);
        tv_music=(TextView)findViewById(R.id.tv_music);
        seekBar=(SeekBar)findViewById(R.id.seekBar_music);
        root_Layout=findViewById(R.id.activity_main);

    }
    //注册广播接收器
    private  void bindReceiver(){

         //注册MusicBroadcastReceiver
        IntentFilter musicFilter=new IntentFilter("android.intent.action.Music_BroadcastReceiver");
        musicReceiver=new MusicBroadcastReceiver();
        registerReceiver(musicReceiver,musicFilter);

        //注册StatusChangedReceiver
        IntentFilter ststusfilter=new IntentFilter("android.intent.action.Music_StatusChangedReceiver");
        statusChangedReceiver=new StatusChangedReceiver();
        registerReceiver(statusChangedReceiver,ststusfilter);

    }
    //改变图标状态的接收器
    private class StatusChangedReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {

            music_State=intent.getIntExtra("status",MediaPlayerUser.MUSIC_STATUS_ERROR);
            Message message=Message.obtain();
            switch (music_State){

                case MediaPlayerUser.MUSIC_STATUS_PAUSED:   imgBtn_Play.setBackgroundResource(R.drawable.button_play);
                                                                 message.what=PROGRESS_PAUSE;
                                                                 seekBarHandler.sendMessage(message);break;
                case MediaPlayerUser.MUSIC_STATUS_STARTED:  imgBtn_Play.setBackgroundResource(R.drawable.button_pause);
                                                                currentTime=intent.getIntExtra("currentTime",currentTime);
                                                                durationTime=intent.getIntExtra("musicDuration",0);
                                                                message.what=PROGRESS_INCREASE;
                                                                seekBarHandler.sendMessage(message);break;

                case MediaPlayerUser.MUSIC_STATUS_STOP:      imgBtn_Play.setBackgroundResource(R.drawable.button_play);
                                                                 message.what=PROGRESS_RESET;
                                                                 seekBarHandler.sendMessage(message); break;
                case MediaPlayerUser.MUSIC_STATUS_ERROR:break;
            }
            //显示正在播放的音乐
            if (music_State!=mediaPlayerUser.MUSIC_STATUS_STOP&&music_State!=MediaPlayerUser.MUSIC_STATUS_ERROR){
                String musicname=intent.getStringExtra("musicName");
                String musicArtist=intent.getStringExtra("musicArtist");
                setTitle("正在播放:"+musicname+"-"+musicArtist);
                tv_music.setText(musicname+"-"+musicArtist);
            }else {
                setTitle("GracePlayer");
                tv_music.setText("");
            }

        }
    }
    //发送广播
    private  void sendBroadcast_Choose(int status, int i){

       Intent intent=new Intent("android.intent.action.Music_BroadcastReceiver");
        Message message=Message.obtain();
        switch (status){
            case MediaPlayerUser.MUSIC_COMMAND_PALY:intent.putExtra("status",MediaPlayerUser.MUSIC_COMMAND_PALY);break;
            case MediaPlayerUser.MUSIC_COMMAND_STOP:intent.putExtra("status",MediaPlayerUser.MUSIC_COMMAND_STOP);break;
            case  MediaPlayerUser.MUSIC_COMMAND_PREVIOUS:intent.putExtra("status",MediaPlayerUser.MUSIC_COMMAND_PREVIOUS);break;
            case  MediaPlayerUser.MUSIC_COMMAND_NEXT:intent.putExtra("status",MediaPlayerUser.MUSIC_COMMAND_NEXT);break;
            case MediaPlayerUser.MUSIC_COMMAND_ONCLICKITEM_NUMBER:intent.putExtra("status",MediaPlayerUser.MUSIC_COMMAND_ONCLICKITEM_NUMBER);intent.putExtra("number",i);break;
            case MediaPlayerUser.MUSIC_COMMAND_SEEKTO:intent.putExtra("status",MediaPlayerUser.MUSIC_COMMAND_SEEKTO);intent.putExtra("currentTime",currentTime);Log.v("see",""+intent.getIntExtra("currentTime",1));break;
        }
      sendBroadcast(intent);
    }

    //获得手机SDcard的音乐信息
     private void initMusicList(){

        musicArrayList= Sdcard_MusicList.getMusicArrayList(this);

    }


    //点击事件绑定
    private void registerListener(){

        imgBtn_Previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

           sendBroadcast_Choose(MediaPlayerUser.MUSIC_COMMAND_PREVIOUS,0);
            }
        });
        imgBtn_Play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            sendBroadcast_Choose(MediaPlayerUser.MUSIC_COMMAND_PALY,0);
            }
        });
        imgBtn_Stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                sendBroadcast_Choose(MediaPlayerUser.MUSIC_COMMAND_STOP,0);
            }
        });
        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                sendBroadcast_Choose(MediaPlayerUser.MUSIC_COMMAND_NEXT,0);

            }
        });
       list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

               sendBroadcast_Choose(MediaPlayerUser.MUSIC_COMMAND_ONCLICKITEM_NUMBER,i);
           }
       });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {


            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if( music_State!= mediaPlayerUser.MUSIC_STATUS_STOP){
                    currentTime =seekBar.getProgress();
                    Log.v("Progress",currentTime+"");
                    //更新文本
                   tv_currentTime.setText(FormatUntils.ms_Format_minANDs(currentTime));
                    //发送广播给Musicservice,执行跳转
                    sendBroadcast_Choose(MediaPlayerUser.MUSIC_COMMAND_SEEKTO,0);
                }
//                if(music_State== mediaPlayerUser.MUSIC_STATUS_STARTED){
//                    //发送广播给MusicService，执行跳转
//                    sendBroadcast_Choose(MediaPlayerUser.MUSIC_COMMAND_SEEKTO,0);
//
//
//                }
            }
        });
    }
    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (currentTime <=durationTime) {
                            seekBarHandler.removeMessages(PROGRESS_INCREASE);//防止播放中跳转其他歌曲的时候造成消息队列递增
                            Log.v("seekbar","seek");
                            seekBar.setMax(durationTime);
                            seekBar.setProgress(currentTime);
                            seekBar.incrementProgressBy(1000);//进度条+1
                            //延迟一秒发送
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //设置进度条文本
                            tv_durationTime.setText(FormatUntils.ms_Format_minANDs(durationTime));
                            tv_currentTime.setText(FormatUntils.ms_Format_minANDs(currentTime));
                            currentTime += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        //暂停进度条
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        tv_currentTime.setText("00:00");
                        tv_durationTime.setText("00:00");
                        break;
                }
            }
        };
    }

    /*创建菜单*/
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.main, menu);
        //创建该菜单的时候实例化ThemeUntils并初始化对象
        initThemeUntils();
        return super.onCreateOptionsMenu(menu);
    }

    /*处理菜单点击事件*/
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            //显示列表对话框
            case R.id.menu_theme:
                new AlertDialog.Builder(this).setTitle("请选择主题").setItems(R.array.theme,
                                new DialogInterface.OnClickListener(){
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //设置Activity的主题
                                    themeUntils.setTheme(which);

                                    }
                                }).show();
                break;
            case R.id.menu_about:
                //显示文本对话框
                new AlertDialog.Builder(MainActivity.this).setTitle("GracePlayer")
                        .setMessage(R.string.about2).show();
                break;
            case R.id.menu_quit:
                //退出程序
                new AlertDialog.Builder(MainActivity.this).setTitle("提示")
                        .setMessage(R.string.quit_message).setPositiveButton("确定",new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface arg0, int arg1) {
                        System.exit(0);
                    }
                }).setNegativeButton("取消",  new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                }).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //实例化并初始化一个ThemeUntils对象
    protected void initThemeUntils() {
      themeUntils=new ThemeUntils(this,root_Layout);
    }

    //检查SD卡是否存在音乐,限制用户操作
    private void checkMusicFile(){

           if(musicArrayList.isEmpty()){

               imgBtn_Next.setEnabled(false);
               imgBtn_Play.setEnabled(false);
               imgBtn_Previous.setEnabled(false);
               imgBtn_Stop.setEnabled(false);
               makeText(MainActivity.this,this.getString(R.string.musiclist_null), LENGTH_SHORT).show();
           }
           else{

               imgBtn_Next.setEnabled(true);
               imgBtn_Play.setEnabled(true);
               imgBtn_Previous.setEnabled(true);
               imgBtn_Stop.setEnabled(true);
           }
    }

   //将获得的音乐信息根据需要以列表元素信息显示
    private  void initListView(){

         list.setAdapter(new MyAdapter());

    }
    //自定义适 配器
    class MyAdapter extends BaseAdapter{
        @Override
        public int getCount() {
            return musicArrayList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View v;
            if(view==null){

                v=View.inflate(MainActivity.this,R.layout.listview_items,null);
            }else{

                v=view;
            }
            TextView tv_number=(TextView)v.findViewById(R.id.tv_listview_item_number);
            TextView tv_title=(TextView)v.findViewById(R.id.tv_listview_item_title);
            TextView tv_artist=(TextView)v.findViewById(R.id.tv_listview_item_artist);
            tv_artist.setText(musicArrayList.get(i).getmusicArtist());
            tv_title.setText(musicArrayList.get(i).getmusicName());
            tv_number.setText(i+"");

            return v;
        }
    }
}
